package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.common.to.HasStockTo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundsTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuSaleAttrValueService saleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存spu以及sku对应信息
     *
     * @param skuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SkuSaveVo skuSaveVo) {
        //1.保存spu基本信息 spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(skuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());

        this.save(spuInfoEntity);

        //2.保存spu的描述图片 spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        Long spuId = spuInfoEntity.getId();
        List<String> decript = skuSaveVo.getDecript();
        String joinedDescript = String.join(",", decript);
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(joinedDescript);

        spuInfoDescService.save(spuInfoDescEntity);

        //3.保存spu的图片集 spu_images
        List<String> images = skuSaveVo.getImages();
        spuImagesService.saveImages(spuId, images);

        //4.保存spu的规格参数 product_attr_value
        List<BaseAttrs> baseAttrs = skuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntities = null;
        if (baseAttrs != null && baseAttrs.size() > 0) {
            attrValueEntities = baseAttrs.stream().map(item -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                Long attrId = item.getAttrId();
                String attrValues = item.getAttrValues();
                int showDesc = item.getShowDesc();
                productAttrValueEntity.setSpuId(spuId);
                productAttrValueEntity.setAttrId(attrId);
                productAttrValueEntity.setAttrValue(attrValues);
                productAttrValueEntity.setQuickShow(showDesc);
                return productAttrValueEntity;
            }).collect(Collectors.toList());
        }

        productAttrValueService.saveBatch(attrValueEntities);
        //5.spu的积分信息 sms.spu_bounds
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        Bounds bounds = skuSaveVo.getBounds();
        if (bounds != null) {
            BeanUtils.copyProperties(bounds, spuBoundsTo);
            spuBoundsTo.setSpuId(spuId);

            R r = couponFeignService.saveSpuBounds(spuBoundsTo);
            if (r.getCode() != 0) {
                log.error("远程调用积分服务失败");
            }
        }
        //6.保存spu对应的sku信息
        //1.基本信息 sku_info
        List<Skus> skus = skuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            for (Skus item : skus) {
                List<Images> imagesList = item.getImages();

                String defaultImage = null;
                for (Images entity : imagesList) {
                    if (entity.getDefaultImg() == 1) {
                        defaultImage = entity.getImgUrl();
                        break;
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSkuDesc(skuSaveVo.getSpuDescription());
                skuInfoEntity.setBrandId(skuSaveVo.getBrandId());
                skuInfoEntity.setCatalogId(skuSaveVo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                //1.保存sku基本信息
                skuInfoService.save(skuInfoEntity);

                List<SkuImagesEntity> skuImagesEntities = null;
                if (imagesList != null && imagesList.size() > 0) {
                    skuImagesEntities =
                            imagesList.stream().map(img -> {
                                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                                        skuImagesEntity.setImgUrl(img.getImgUrl());
                                        if (img.getDefaultImg() == 0) {
                                            skuImagesEntity.setDefaultImg(0);
                                        } else {
                                            skuImagesEntity.setDefaultImg(1);
                                        }
                                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                                        return skuImagesEntity;
                                    }).filter(img ->
                                            //过滤sku图片为空的数据
                                            StringUtils.isNotEmpty(img.getImgUrl()))
                                    .collect(Collectors.toList());
                    //2.图片信息 sku_images
                    skuImagesService.saveBatch(skuImagesEntities);
                }

                //3.销售属性信息 sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> AttrValueEntities = null;
                if (attr != null && attr.size() > 0) {
                    AttrValueEntities =
                            attr.stream().map(a -> {
                                SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                                BeanUtils.copyProperties(a, attrValueEntity);
                                attrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                                return attrValueEntity;
                            }).collect(Collectors.toList());
                    saleAttrValueService.saveBatch(AttrValueEntities);
                }


                //4.满减，优惠信息；sms.sku_ladder,sku_full_reduction,member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                skuReductionTo.setDiscount(item.getDiscount());
                skuReductionTo.setAddOther(0);
                skuReductionTo.setFullCount(item.getFullCount());
                skuReductionTo.setFullPrice(item.getFullPrice());
                skuReductionTo.setReducePrice(item.getReducePrice());
                skuReductionTo.setMemberPrice(item.getMemberPrice());
                if (skuReductionTo.getFullCount() != null || skuReductionTo.getFullPrice() != null || (skuReductionTo.getMemberPrice() != null && skuReductionTo.getMemberPrice().size() > 0)) {
                    R r2 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r2.getCode() != 0) {
                        log.error("远程调用优惠打折服务失败");
                    }
                }
            }

        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String status = (String) params.get("status");
        //封装查询条件
        wrapper.and(StringUtils.isNotEmpty(key), w -> {
            w.eq(SpuInfoEntity::getId, key)
                    .or()
                    .like(SpuInfoEntity::getSpuName, key);
        });
        wrapper.eq(StringUtils.isNotEmpty(catelogId) && !catelogId.equals("0"), SpuInfoEntity::getCatalogId, catelogId)
                .eq(StringUtils.isNotEmpty(brandId) && !brandId.equals("0"), SpuInfoEntity::getBrandId, brandId)
                .eq(StringUtils.isNotEmpty(status) && !status.equals("0"), SpuInfoEntity::getPublishStatus, status);

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 完成spu的上架功能
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {

        SpuInfoEntity spuInfoEntity = this.getById(spuId);

        //2.封装skuEs的数据
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getBySpuId(spuId);
        QueryWrapper<ProductAttrValueEntity> w = new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId);
        List<ProductAttrValueEntity> valueEntities = productAttrValueService.list(w);

        List<Long> AttrIds = valueEntities.stream().map(item ->
                item.getAttrId()).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.getSearchAttrId(AttrIds);

        Set setSearchIds = new HashSet(searchAttrIds);

        List<SkuEsModel.Attrs> attrsList = valueEntities.stream().filter(item ->
                setSearchIds.contains(item.getAttrId())
        ).map(item -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());

        //收集skuid
        List<SkuInfoEntity> skus = skuInfoService.getBySpuId(spuId);
        List<Long> skusIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //TODO 1.hasStock 远程调用库存服务
        HashMap<Long, HasStockTo> map = new HashMap<>();
        Map<Long, Boolean> stockToMap = null;
        try {
            R r = wareFeignService.getHasStock(skusIds);
            List<HasStockTo> data = r.getData(new TypeReference<List<HasStockTo>>() {
            });
            if(data!=null&&data.size()>0){
                stockToMap = data.stream().collect(Collectors.toMap(HasStockTo::getSkuId, item -> item.getStock()));
            }
        } catch (Exception e) {
            log.error("调用远程ware服务出现异常" + e.getStackTrace());
        }
        Map<Long, Boolean> finalStockToMap = stockToMap;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            //   brandImg catalogName attrs
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //TODO 1.hasStock 远程调用库存服务
            if (finalStockToMap != null) {
                skuEsModel.setHasStock(finalStockToMap.get(sku.getSkuId()));
            } else {
                skuEsModel.setHasStock(true);
            }
            //TODO 2.hotpot
            skuEsModel.setHotScore(0L);

            //TODO 3.brandName brandImg brandName
            BrandEntity brand = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandId(brand.getBrandId());
            skuEsModel.setBrandImg(brand.getLogo());
            skuEsModel.setBrandName(brand.getName());

            //TODO 4.catalogName
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(category.getName());

            //TODO 5.规格参数（可展示的）

            skuEsModel.setAttrs(attrsList);

            return skuEsModel;

        }).collect(Collectors.toList());
        //3.发送到es进行保存
        R r = searchFeignService.esSkuUp(skuEsModels);

        if(r.getCode()==0){
            //上架成功，修改spu状态
            //1.修改spu状态
            baseMapper.updateStatusById(spuId, ProductConstant.SpuConstant.SPU_UP.getCode());
        }
        else{
            //上架失败
            //TODO 重复调用，接口幂等性
        }
    }

    @Override
    public SpuInfoEntity spuinfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        Long spuId = skuInfo.getSpuId();
        SpuInfoEntity spuInfoEntity = this.getById(spuId);
        return spuInfoEntity;
    }

}